//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo } from '@/api/user'
//引入数据类型
import type { loginForm, loginResponseData, userResponseData } from '@/api/user/type'
import type { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由（常量路由）
import { constantRoute } from '@/router/routes'

//创建用户小仓库
let useUserStore = defineStore('User', {
  //存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用用户唯一标识token
      menuRoutes: constantRoute, //仓库存储生成菜单需要的数组（路由）
      username: '',
      avatar: ''
    }
  },
  //异步、逻辑的地方
  actions: {
    async userLogin(data: loginForm) {
      let result: loginResponseData = await reqLogin(data)
      //成功200
      //失败201
      if (result.code == 200) {
        this.token = result.data.token as string
        SET_TOKEN(result.data.token as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data.message))
      }
    },
    async userInfo() {
      let result: userResponseData = await reqUserInfo()
      if (result.code == 200) {
        this.username = result.data.checkUser.username
        this.avatar = result.data.checkUser.avatar
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败！')
      }
    },
    userLogout() {
      //目前没有mock退出登录的接口（通知服务器本次用户唯一标识失效）
      this.token = ''
      this.username = ''
      this.avatar = ''
      //还需要清除本次存储的token
      REMOVE_TOKEN()
    }
  },
  //计算属性
  getters: {}
})

//对外暴露获取小仓库方法
export default useUserStore
